import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';
import '../../../const/AppConst.dart';
import '../../../event/MsgContentEvent.dart';
import '../../../logger/Logger.dart';
import '../../../models/Devices.dart';
import '../../../storage/StorageManager.dart';
import '../../../widget/tips.dart';
class MineViewController extends GetxController {
  var mUserNickName = ''.obs;
  var hasBindRobot = false.obs;
  var dSN = ''.obs;

  Rx<Device> currentSelectedDevice = Device().obs;


  @override
  void onInit() {
    super.onInit();

    currentSelectedDevice.value  = CommonUtil.getCurrentSelectedRobot();

    initData();

  }

  void initData() {
      Map user = StorageManager.getStorage().read(AppConst.storage_current_login_user);
      mUserNickName.value = user['nickName'];
      // freshDevice();


      if (currentSelectedDevice.value!.robotUserId != null) {
        hasBindRobot.value = true;
      } else {
        hasBindRobot.value = false;
      }

      if(StorageManager.getStorage().hasData(AppConst.BLT_DEVICE_SN_CURRENTLY)) {
        dSN.value = StorageManager.getStorage().read(AppConst.BLT_DEVICE_SN_CURRENTLY);
      }

      eventBus.on<ProductContentEvent>().listen((event) {
         logger.info('i can hear you. ${event}');
         ProductContentEvent productContentEvent =  event as ProductContentEvent;

         if (productContentEvent.code == ROBOT_LIST_HAVE_CHANGED) {

           if (CommonUtil.getMyRobotLists().isNotEmpty) {
             hasBindRobot.value = true;
           } else {
             hasBindRobot.value = false;
           }

           currentSelectedDevice.value = CommonUtil.getCurrentSelectedRobot();
           if (currentSelectedDevice.value!.robotUserId != null) {
             dSN.value = currentSelectedDevice.value!.robotUserId!;
           }
         } else if (productContentEvent.code == ACCOUNT_INFO_REFRESH) {
           Map user = StorageManager.getStorage().read(AppConst.storage_current_login_user);
           mUserNickName.value = user['nickName'];
         }

      });

  }



  void freshDevice(List v) {
    if (v != null && v.length > 0) {
      hasBindRobot.value = true;
      if(StorageManager.getStorage().hasData(AppConst.BLT_DEVICE_SN_CURRENTLY)) {
        dSN.value = StorageManager.getStorage().read(AppConst.BLT_DEVICE_SN_CURRENTLY);
      }

    } else {
      hasBindRobot.value = false;
      dSN.value = '';
    }
  }


  void copyTextToClipboard(String snNumber) async {
    try {
      await Clipboard.setData(ClipboardData(text: snNumber));
      Tips.showToast('已复制序列号');
    } catch (e) {
       e.printInfo();
    }
  }

}